#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <network_manager.h>
#include <config.h>

static int clientInit(void);
static int clientExit(void);
static int clientConnect(void);
static int clientSend(char *buff, int lenth);
static int clientRecv(char *buff, int lenth);

static T_networkOpr client = 
{
	.name			= "client",
	.networkInit 	= clientInit,
	.networkExit 	= clientExit,
	.networkConnect = clientConnect,
	.networkSend 	= clientSend,
	.networkRecv 	= clientRecv,
	.next			= NULL,
};

static int clientInit(void)
{
	client.fd = socket(AF_INET,SOCK_STREAM,0);	
	if(client.fd <0)
	{
		fprintf(stderr,"socket error:%s\n",strerror(errno));
		return -1;
	}

	return 0;
}

static int clientExit(void)
{
	close(client.fd);

	return 0;
}

static int clientConnect(void)
{
	struct sockaddr_in raddr;
	int ret,value;

	value =1;
	ret = setsockopt(client.fd,SOL_SOCKET,SO_REUSEPORT,&value,sizeof(value));
	if(ret <0)
	{
		fprintf(stderr,"setsockopt error:%s\n",strerror(errno));
		return -1;
	}

	raddr.sin_family = AF_INET;
	raddr.sin_port	 = htons(atoi(SERVER_PORT));
	inet_pton(AF_INET,SERVER_IP,&raddr.sin_addr.s_addr);

tryagain:
	ret = connect(client.fd,(void *)&raddr,sizeof(raddr));
	if(ret <0)
	{
		if(errno == EINTR|| errno ==EAGAIN)
			goto tryagain;
	
		fprintf(stderr,"connect error:%s\n",strerror(errno));
		return -1;
	}

	return 0;
}

static int clientSend(char *buff, int lenth)
{
	int ret;
	
	ret = send(client.fd, buff, lenth, 0);
	return ret;
}

static int clientRecv(char *buff, int lenth)
{
	int ret;

	ret = recv(client.fd, buff, lenth, 0);
	return ret;
}

int clientNetWorkInit(void)
{
	int ret;
	
	ret = registerNetWork(&client);
	return ret;
}


